package com.internetCafes.spms.common.utils.wechat;

import net.sf.json.JSONObject;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import java.util.HashMap;
import java.util.Map;

public class WechatOpenIdUtil {

    private static final String APP_ID = "wxbede07c77b1fba90";
    private static final String APP_SECRET = "1047a08bd399134d39346db31f81b8ca";

    // 网页授权接口
//    public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";//
//    public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code";
    private final static String URL_OAUTH = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code";

    public static Map<String, String> getOauthInfo(String code) {
        String requestUrl = URL_OAUTH.replace("APPID", APP_ID).replace("SECRET", APP_SECRET).replace("CODE", code);
        HttpClient client = null;
        Map<String, String> result = new HashMap<>();
        try {
            client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(requestUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(httpget, responseHandler);
            JSONObject OpenidJSONO = JSONObject.fromObject(response);
            String openid = String.valueOf(OpenidJSONO.get("openid"));
            String session_key = String.valueOf(OpenidJSONO.get("session_key"));
            String unionid = String.valueOf(OpenidJSONO.get("unionid"));
            String errcode = String.valueOf(OpenidJSONO.get("errcode"));
            String errmsg = String.valueOf(OpenidJSONO.get("errmsg"));

            result.put("openid", openid);
            result.put("sessionKey", session_key);
            result.put("unionid", unionid);
            result.put("errcode", errcode);
            result.put("errmsg", errmsg);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getConnectionManager().shutdown();
        }
        return result;
    }
}
